package arrayList;

import java.util.Arrays;

public class MyArrayList implements IArrayList{
    int[] elem;
    int usedSize;
    //默认长度
    int DEFAULT_LENGTH = 10;
    //指定长度构造方法
    public MyArrayList() {
        elem = new int[DEFAULT_LENGTH];
    }

    @Override
    public void add(int data) {
        if(isEmpty()) {
            this.elem = Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize] = data;
        usedSize++;
    }

    @Override
    public void add(int pos, int data) {
        if(isEmpty()) {
            this.elem = Arrays.copyOf(elem,2*elem.length);
        }
        if(pos<0 || pos>usedSize) {
            throw new MyException("pos位置不合法");
        }
        for (int i = usedSize-1; i >= pos; i--) {
            elem[i+1] = elem[i];
        }
        elem[pos] = data;
        usedSize++;
    }

    @Override
    public boolean contains(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if(elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int indexOf(int toFind) {
        for (int i = 0; i < usedSize; i++) {
            if(elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    @Override
    public int get(int pos) {
        if(pos < 0 || pos >= usedSize) {
            throw new MyException("pos位置不合法");
        }
        return elem[pos];
    }

    @Override
    public void set(int pos, int value) {
        if(pos < 0 || pos >= usedSize) {
            throw new MyException("pos位置不合法");
        }
        elem[pos] = value;
    }

    @Override
    public void remove(int toRemove) {
        int pos = indexOf(toRemove);
        for (int i = pos; i < usedSize-1; i++) {
            elem[i] = elem[i+1];
        }
        usedSize--;
    }
    @Override
    public int size() {
        return usedSize;
    }

    @Override
    public void clear() {
        //之间置为0
        usedSize = 0;
        //引用类型要使用循环制空
        for (int i = 0; i < usedSize; i++) {
            elem[i] = 0;
        }
    }

    @Override
    public void display() {
        for (int i = 0; i < usedSize;i++) {
            System.out.print(elem[i] + " ");
        }
    }

    @Override
    public boolean isEmpty() {
        return usedSize == elem.length;
    }
}
